package com.liuzy.executor;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;

/**
 * WindowsCMD执行者
 * 
 * @author liuzy
 * @version 2015年5月2日
 */
public class WinCmder extends Executor implements IExecutor {

	/** 执行cmd.exe的进程 */
	private Process p = null;
	
	/** cmd.exe的正常消息输出进程 */
	private Thread inThread = null;
	
	/** cmd.exe错误消息输出进程 */
	private Thread outThread = null;
	
	public WinCmder(InputStream in, OutputStream out) {
		this.in = in;
		this.out = out;
		this.init();
	}

	@Override
	public void init() {
		try {
			p = Runtime.getRuntime().exec("cmd");
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		// 把cmd.exe返回的正常消息流按字符写到客户端的out
		inThread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					boolean flag = true;
					Reader reader = new InputStreamReader(WinCmder.this.p.getInputStream(), "GBK");
					int size = -1;
					char[] buf = new char[1024];
					while (true) {
						size = reader.read(buf);
						if (size != -1) {
							if (flag) {
								// 去掉版本信息
								for (int i = 0; i < buf.length; i++) {
									if (buf[i] == ':') {
										WinCmder.this.writeMsg(new String(buf, i-1, size).getBytes("UTF-8"));
										flag = false;
										break;
									}
								}
							} else {
								WinCmder.this.writeMsg(new String(buf, 0, size).getBytes("UTF-8"));
							}
						} else {
							break;
						}
					}
					reader.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		inThread.start();
		// 把cmd.exe返回的错误消息流按字符写到客户端的out
		outThread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Reader reader = new InputStreamReader(WinCmder.this.p.getErrorStream(), "GBK");
					int size = -1;
					char[] buf = new char[1024];
					while (true) {
						size = reader.read(buf);
						if (size != -1) {
							WinCmder.this.writeMsg(new String(buf, 0, size-1).getBytes("UTF-8"));
						} else {
							break;
						}
					}
					reader.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		outThread.start();
		this.writeMsg("**************\r\ncmd.exe已打开!\r\n退出请输入exit回车.\r\n");
		
	}

	@Override
	public void execute(String cmd) {
		PrintWriter pw = new PrintWriter(p.getOutputStream());
		if ("".equals(cmd)) {
			pw.print("\r\n");
		} else {
			pw.print(cmd + "\r\n");
		}
		pw.flush();
	}

	@Override
	public void destroy() {
		p.destroy();
		inThread.interrupt();
		outThread.interrupt();
	}

}
